package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import com.yt.sys.models.service.IPermissionService;
import com.yt.sys.models.bo.PermissionBO;
import com.yt.sys.models.dto.PermissionDTO;
import com.yt.sys.models.bo.PermissionSaveBO;

import java.util.List;

/**
 * 权限信息控制器
 *
 * @author yzz
 * @Date 2025-10-22 09:47:20
 */

@RestController
@RequestMapping("/api/permission")
@Slf4j
@Api(value = "PermissionApiController",tags = "权限信息Api接口")
public class PermissionApiController {

    @DubboReference
    private IPermissionService permissionService;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<PermissionDTO> get(@RequestParam("id") Long id){
        if(id == null){
            Result<PermissionDTO> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100002.getCode());
            result.setMsg(CodeEnum.FAIL_100002.getMsg());
            return result;
        }

        PermissionDTO dto = permissionService.selectById(id);
        
        Result<PermissionDTO> result = new Result<>();
        result.setData(dto);
        return result;
    }

    @ApiOperation(value = "权限信息列表",notes = "权限信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<PermissionDTO>> queryPageList(PermissionBO bo){
        Wrapper<PermissionDTO> wrapper = new EntityWrapper<>();
                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<PermissionDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = permissionService.selectPage(page, wrapper);

        Result<Page<PermissionDTO>> result = new Result<>();
        result.setData(page);
        return result;
    }
    
    @ApiOperation(value = "获取所有权限信息", notes = "获取所有权限信息")
    @PostMapping("/listAll")
    public Result<List<PermissionDTO>> listAll() {
        List<PermissionDTO> permissionList = permissionService.selectList(null);
        
        Result<List<PermissionDTO>> result = new Result<>();
        result.setData(permissionList);
        return result;
    }
    
    @ApiOperation(value = "新增权限", notes = "新增权限")
    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody PermissionSaveBO saveBO) {
        try {
            Result<Boolean> result = new Result<>();
            // 参数校验
            if (saveBO == null) {
                result.setData(false);
                result.setCode(CodeEnum.FAIL_100002.getCode());
                result.setMsg("参数不能为空");
                return result;
            }
            
            // 执行新增操作
            boolean operationResult = permissionService.add(saveBO);
            if (operationResult) {
                result.setData(true);
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg("新增权限成功");
            } else {
                result.setData(false);
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg("新增权限失败");
            }
            return result;
        } catch (Exception e) {
            log.error("新增权限异常", e);
            Result<Boolean> result = new Result<>();
            result.setData(false);
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("新增权限异常：" + e.getMessage());
            return result;
        }
    }
    
    @ApiOperation(value = "修改权限", notes = "修改权限")
    @PostMapping("/update")
    public Result<Boolean> update(@RequestBody PermissionSaveBO saveBO) {
        try {
            Result<Boolean> result = new Result<>();
            // 参数校验
            if (saveBO == null || saveBO.getId() == null || saveBO.getId().trim().isEmpty()) {
                result.setData(false);
                result.setCode(CodeEnum.FAIL_100002.getCode());
                result.setMsg("参数不能为空，权限ID不能为空");
                return result;
            }
            
            // 先查询权限是否存在
            Long permissionId;
            try {
                permissionId = Long.valueOf(saveBO.getId());
            } catch (NumberFormatException e) {
                result.setData(false);
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg("权限ID格式不正确");
                return result;
            }
            
            PermissionDTO existingPermission = permissionService.selectById(permissionId);
            if (existingPermission == null) {
                result.setData(false);
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg("权限不存在");
                return result;
            }
            
            // 将PermissionSaveBO转换为PermissionDTO
            PermissionDTO permissionDTO = new PermissionDTO();
            permissionDTO.setPermissionId(saveBO.getId()); // 使用String类型的ID
            permissionDTO.setPermissionName(saveBO.getPermissionName());
            permissionDTO.setPermissionCode(saveBO.getPermissionCode());
            permissionDTO.setType(saveBO.getType());
            permissionDTO.setUrl(saveBO.getUrl());
            permissionDTO.setStatus(saveBO.getStatus());
            
            // 执行更新操作
            boolean operationResult = permissionService.updateById(permissionDTO);
            if (operationResult) {
                result.setData(true);
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg("修改权限成功");
            } else {
                result.setData(false);
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg("修改权限失败");
            }
            return result;
        } catch (Exception e) {
            log.error("修改权限异常", e);
            Result<Boolean> result = new Result<>();
            result.setData(false);
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("修改权限异常：" + e.getMessage());
            return result;
        }
    }
    
    @ApiOperation(value = "删除权限", notes = "删除权限")
    @PostMapping("/delete")
    @ApiImplicitParam(name = "id", value = "权限ID", required = true, paramType = "query", dataType = "Long")
    public Result<Boolean> delete(@RequestParam("id") Long id) {
        try {
            Result<Boolean> result = new Result<>();
            // 参数校验
            if (id == null) {
                result.setData(false);
                result.setCode(CodeEnum.FAIL_100002.getCode());
                result.setMsg("参数不能为空，权限ID不能为空");
                return result;
            }
            
            // 先查询权限是否存在
            PermissionDTO existingPermission = permissionService.selectById(id);
            if (existingPermission == null) {
                result.setData(false);
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg("权限不存在");
                return result;
            }
            
            // 执行删除操作，使用String类型的主键
            boolean operationResult = permissionService.deleteById(existingPermission.getPrimaryKey());
            if (operationResult) {
                result.setData(true);
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg("删除权限成功");
            } else {
                result.setData(false);
                result.setCode(CodeEnum.FAIL.getCode());
                result.setMsg("删除权限失败");
            }
            return result;
        } catch (Exception e) {
            log.error("删除权限异常", e);
            Result<Boolean> result = new Result<>();
            result.setData(false);
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("删除权限异常：" + e.getMessage());
            return result;
        }
    }
    
    @ApiOperation(value = "根据权限ID或名称查询权限", notes = "根据权限ID或名称查询权限，支持模糊查询")
    @PostMapping("/search")
    public Result<List<PermissionDTO>> search(@RequestParam(value = "keyword", required = true) String keyword) {
        try {
            Result<List<PermissionDTO>> result = new Result<>();
            // 参数校验
            if (keyword == null || keyword.trim().isEmpty()) {
                result.setCode(CodeEnum.FAIL_100002.getCode());
                result.setMsg(CodeEnum.FAIL_100002.getMsg());
                return result;
            }
            
            // 构造查询条件
            Wrapper<PermissionDTO> wrapper = new EntityWrapper<>();
            wrapper.like("id", keyword).or().like("permission_name", keyword);
            
            // 执行查询
            List<PermissionDTO> permissionList = permissionService.selectList(wrapper);
            
            result.setData(permissionList);
            return result;
        } catch (Exception e) {
            log.error("根据权限ID或名称查询权限异常", e);
            Result<List<PermissionDTO>> result = new Result<>();
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("查询异常：" + e.getMessage());
            return result;
        }
    }
}